﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
using System.Xml;

namespace Fares
{
    public partial class ExportDeclaratiiFrm : FrmRezumat 
    {
        private String CaleD394 = String.Empty;
        private List<Decimal> lista_CUI = new List<decimal>();
        private XmlDocument xmlDoc = new XmlDocument();
        public ExportDeclaratiiFrm(ModuleClass mc) : base(mc)
        {
            workConnString = mc.workConnectionString;
            InitializeComponent();
            declaratieCB.Items.Add("D394");
            anulDTP.Format = DateTimePickerFormat.Custom;
            anulDTP.CustomFormat = "yyyy";
            semestrulCB.Items.Add("semestrul 1");
            semestrulCB.Items.Add("semestrul 2");
            
            trimestrulCB.Items.Add("trimestrul I");
            trimestrulCB.Items.Add("trimestrul II");
            trimestrulCB.Items.Add("trimestrul III");
            trimestrulCB.Items.Add("trimestrul IV");

            SmartCardCB.Items.Add("aladdin");
            SmartCardCB.Items.Add("athena");
            SmartCardCB.Items.Add("gemalto");
            SmartCardCB.Items.Add("oberthur");
            SmartCardCB.Items.Add("safeNet");
            SmartCardCB.Items.Add("schlumberger");
            SmartCardCB.SelectedIndex = 0;
            
            lunaCB.Items.AddRange(new String[] {"Ianuarie","Februarie","Martie","Aprilie","Mai","Iunie","Iulie","August","Septembrie","Octombrie","Noiembrie","Decembrie"});
            semestrulCB.SelectedIndex = 0;
            trimestrulCB.SelectedIndex = 0;
            lunaCB.SelectedIndex = 0;
            semestrulRB.Checked = true;

            delaDTP.Format = DateTimePickerFormat.Custom;
            delaDTP.CustomFormat = "dd.MM.yyyy";
            panalaDTP.Format = DateTimePickerFormat.Custom;
            panalaDTP.CustomFormat = "dd.MM.yyyy";

        }

        private void ExportDeclaratiiFrm_Load(object sender, EventArgs e)
        {
            AddButton("Proceseaza[F9]", global::ERPStudio.Properties.Resources.gear, Proceseaza, ToolStripItemAlignment.Right, true);
            AddButton("Info Unitate", global::ERPStudio.Properties.Resources._001_55, Info, ToolStripItemAlignment.Right, true);
            declaratieCB.SelectedIndex = 0;
            SqlConnection wConn = DeschideConexiune(workConnString);
            #region Determinare luna,an curent
            Object ret = GetSetupValue("FaresSetup", "CaleD394", ModuleInfo.CodUnitate, wConn);
            String val = String.Empty;
            if (ret != null && ret != DBNull.Value)
                val = ret.ToString();
            else
            {
                while (ret == null)
                {
                    MessageBox.Show("Modulul Parteneri nu a fost configurat. \nVa rugam sa-l configurati!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    FaresSetupFrm frm = new FaresSetupFrm(this.ModuleInfo);
                    frm.ShowDialog();
                    ret = GetSetupValue("FaresSetup", "CaleD394", ModuleInfo.CodUnitate, wConn);
                }
            }
            CaleD394 = ret.ToString();
            #endregion
            InchideConexiune(wConn);
        }

        private void Proceseaza(object sender, EventArgs e)
        {
            if (declaratieCB.SelectedIndex == 0)
            {

                Boolean dupa12_2013 = false; // daca declaratia este pentru perioada de dupa 12.2013
                //face backup la fisierul existent
                String NumeFisier = CaleD394 + "D394.txt";
                String NumeFisierXml = CaleD394 + "D394.xml";

                String NumeDest = CaleD394 + "D394." + DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString() + ".bak";
                if (File.Exists(NumeFisier))
                    File.Move(NumeFisier, NumeDest);
                StreamWriter writeS = null;
                try
                {
                    MyTrace("Scrie:" + NumeFisier);
                    writeS = File.CreateText(NumeFisier);
                    
                }
                catch(Exception ex)
                {
                    MessageBox.Show("Va rugam sa setati calea de lansare a programului de declaratii D394 din meniul Parametrizare Modul!", "Atentie");
                    MyTrace("Nu poare scrie: " + NumeFisier + " Cauza: " + ex.Message);
                    return;                
                }
                String sem;
                xmlDoc.AppendChild(xmlDoc.CreateProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"));
                

                //XmlElement el = xmlDoc.CreateElement("declaratia394");
  

                //-<declaratie394 xmlns="mfp:anaf:dgti:d394:declaratie:v1" xsi:schemaLocation="mfp:anaf:dgti:d394:declaratie:v1 D394.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" functie_declar="ADM" prenume_declar="DORIN" nume_declar="POPA" tip_D394="L" an="2012" luna="6"> <identificare totalPlata_A="1126939" mail="dorin.popa@datastudio.ro" telefon="0744143461" adresa="victor babes 13" den="Tribunalul Maramures" cui="18162617"/> <idReprezentant mailR="dorin.popa@datastudio.ro" telefonR="0744143461" adresaR="victor babes 39" denR="popa dorin" cifR="1710517010312"/> <rezumat tvaCc="0" bazaCc="0" tvaC="0" bazaC="0" tvaVc="0" bazaVc="0" tvaV="0" bazaV="0" tvaA="192456" bazaA="801900" tvaL="25661" bazaL="106920" nrCui="2"/> <op1 tva="25661" baza="106920" denP="TOTO S.R.L." cuiP="4004978" tip="L"/> <op1 tva="192456" baza="801900" denP="DRUSAL SA " cuiP="7233879" tip="A"/> </declaratie394>
                //xmlDoc.AppendChild(el);
               //XmlElement identificare = xmlDoc.CreateElement("identificare");
                //XmlElement idReprezentant = xmlDoc.CreateElement("idReprezentant");
                String sb = "<?xml version=\"1.0\"?>\n<declaratie394 xmlns=\"mfp:anaf:dgti:d394:declaratie:v1\" xsi:schemaLocation=\"mfp:anaf:dgti:d394:declaratie:v1 D394.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";

                if (anulDTP.Value.Year * 100 + panalaDTP.Value.Month >= 201312)
                    dupa12_2013 = true;
                if (dupa12_2013 == true)
                {
                    sb = "<?xml version=\"1.0\"?>\n<declaratie394 xmlns=\"mfp:anaf:dgti:d394:declaratie:v2\" xsi:schemaLocation=\"mfp:anaf:dgti:d394:declaratie:v1 D394.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
                }
                //"></declaratie394>";
                //xmlDoc.LoadXml();
                //XmlNamespaceManager nsmanager = new XmlNamespaceManager(xmlDoc.NameTable);
                //XmlElement el = xmlDoc.DocumentElement;
                String _tipPlatitor = "L";
                using(SqlConnection wCon = DeschideConexiune(workConnString))
                {
                    this.unitatiTableAdapter.Connection = wCon;
                    this.unitatiTableAdapter.Fill(this.eSRPDataSetListe.Unitati, ModuleInfo.CodUnitate);
                    if (unitatiBindingSource.Count == 0)
                    {
                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Modulul nu a fost configurat inca!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, null);
                        mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.ShowDialog();
                        // modulul nu este configurat
                        return;
                    }

                    sem = String.Empty;
                    if (semestrulRB.Checked)
                    {
                        switch (semestrulCB.SelectedIndex)
                        {
                            case 0:
                                sem += "6";
                                break;
                            default:
                                sem = "12";
                                break;
                        }
                        sb += " tip_D394=\"S\" " ;
                        _tipPlatitor = "L";
                        
                    }
                    else
                        if (trimestrulRB.Checked)
                        {
                            switch (trimestrulCB.SelectedIndex)
                            {
                                case 0:
                                    sem += "3";
                                    break;
                                case 1:
                                    sem += "6";
                                    break;
                                case 2:
                                    sem += "9";
                                    break;
                                default:
                                    sem = "12";
                                    break;
                            }
                            sb += " tip_D394=\"T\" ";
                            _tipPlatitor = "T";
                        }
                        else if (lunaRB.Checked)
                        {
                            sem += (lunaCB.SelectedIndex + 1).ToString();
                            if (sem.Length == 1)
                                sem = "0" + sem;
                            _tipPlatitor = "L";
                            sb += " tip_D394=\"L\" ";
                        }
                    sb += " luna=\"" + sem + "\" ";
                    sb += " an=\"" + anulDTP.Value.Year.ToString() +"\" ";
                    //el.SetAttribute("luna", sem);
                    

                    sem ="394," +sem+  ","+anulDTP.Value.Year.ToString();
                    DataSets.ESRPDataSetListe.UnitatiRow ur = ((DataRowView)unitatiBindingSource.Current).Row as DataSets.ESRPDataSetListe.UnitatiRow;

                    String nume = String.Empty, prenume = String.Empty;

                    if (!string.IsNullOrEmpty(ur.Reprezentant))
                    {
                        int retspa = ur.Reprezentant.IndexOf(' ');
                        if (retspa != -1)
                        {
                            nume = ur.Reprezentant.Substring(0, retspa);
                            prenume = ur.Reprezentant.Substring(retspa + 1);
                        }
                    }

                    writeS.WriteLine(sem + ",#" + _tipPlatitor +"#,#" + nume + "#,#" + prenume + "#,#" +
                        (ur.IsFunctieReprezentantNull()?"Administrator":ur.FunctieReprezentant)+ "#," + ur.CUI.ToString() 
                        + ",#" + ur.Denumire + "#,#" + (ur.IsAdresaNull()?"":ur.Adresa) +
                        "#,#" + (ur.IsTelefonNull()?"":ur.Telefon) + "#,#" + (ur.IsFaxNull()?"":ur.Fax) + "#,#" + (ur.IsEmailNull()?"":ur.Email) + "#" );
                   
                    String[] pozR = ur.Reprezentant.ToString().Split(new char[]{' '});
                    
                    //el.SetAttribute("functie_declar", dr["FunctieReprezentant"].ToString());
                    sb += " functie_declar=\"" + (ur.IsFunctieReprezentantNull()?"Administrator":ur.FunctieReprezentant) + "\" ";
                    if (pozR.Length >= 1)
                    {
                        //el.SetAttribute("nume_declar", pozR[0]);
                        sb += " nume_declar=\"" + pozR[0] + "\" ";
                    }
                    //else
                    //    el.SetAttribute("nume_declar", String.Empty);
                    if (pozR.Length >= 2)
                    {
                        //el.SetAttribute("prenume_declar", pozR[1]);
                        sb += " prenume_declar=\"" + pozR[1] + "\" ";
                    }
                    //else
                    //    el.SetAttribute("prenume_declar", String.Empty);

                    sb += ">";
                    
                    String sb5 = "\n<idReprezentant";
                    sb5 += " mailR=\"" + (ur.IsEmailReprezentantNull()?"":ur.EmailReprezentant) + "\" ";
                    sb5 += " telefonR=\"" + (ur.IsTelefonReprezentantNull()?"":ur.TelefonReprezentant) + "\" ";
                    sb5 += " adresaR=\"" + (ur.IsAdresaReprezentantNull()?"":ur.AdresaReprezentant) + "\" ";
                    sb5 += " denR=\"" + (ur.IsReprezentantNull()?"":ur.Reprezentant) + "\" ";
                    sb5 += " cifR=\"" + (ur.IsCNPReprezentantNull()?"":ur.CNPReprezentant.ToString()) + "\" ";
                    sb5 += " />";


                    String sbi = " mail=\"" + (ur.IsEmailNull()?"":ur.Email) + "\" ";
                    sbi += " telefon=\"" + (ur.IsTelefonNull()?"":ur.Telefon) + "\" ";
                    sbi += " adresa=\"" + (ur.IsAdresaNull()?"":ur.Adresa) + "\" ";
                    sbi += " den=\"" + ur.Denumire + "\" ";
                    sbi += " cui=\"" + ur.CUI + "\" ";
                    sbi += " />";

                    writeS.Flush();

                    #region Achizitii
                    Decimal? rettotal = Decimal.Zero, rettotaltva = Decimal.Zero;
                    Decimal? nrFactA = Decimal.Zero, nrFactL = Decimal.Zero, nrFactV = Decimal.Zero, nrFactC = Decimal.Zero;
                    try
                    {
                        this.fares_GenereazaD394FacturiTableAdapter.Connection = wCon;
                        this.fares_GenereazaD394FacturiTableAdapter.Fill(this.eSRPDataSetListe.fares_GenereazaD394Facturi,
                            ModuleInfo.CodUnitate,
                            delaDTP.Value,
                            panalaDTP.Value,
                            true/*cumparari*/,/*taxare inversa*/false,
                            excludeNrFactTB.Text,
                            ref rettotal, ref rettotaltva, ref nrFactA);
                    }
                    catch(Exception)
                    {
                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", Properties.Resources.InvalidDatabaseStructure, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, fares_GenereazaD394FacturiTableAdapter);
                        mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.ShowDialog();
                        return;
                    }



                    String sb2 = String.Empty;
                    int CateLinii = 0;
                    lista_CUI.Clear();
                    foreach (DataRowView drv in fares_GenereazaD394FacturiBindingSource)
                    {
                        DataSets.ESRPDataSetListe.fares_GenereazaD394FacturiRow fr = drv.Row as DataSets.ESRPDataSetListe.fares_GenereazaD394FacturiRow;

                        writeS.WriteLine("#A#," + fr.CUI.ToString() + ",#" + fr.Denumire + "#," +
                            //Convert.ToDouble(dr["Total"]).ToString("F2", (CultureInfo.InvariantCulture)) + "," +
                            Convert.ToDouble(fr.TotalValoare).ToString("F2", (CultureInfo.InvariantCulture)) + "," + Convert.ToDouble(fr.TotalValoareTVA).ToString("F2", (CultureInfo.InvariantCulture)));
                        writeS.Flush();
                        //<op1 tva="25661" baza="106920" denP="TOTO S.R.L." cuiP="4004978" tip="L"/>
                        String den = fr.Denumire.Replace("&", "and");
                        sb2 += "\n<op1 tip=\"A\" cuiP=\"" + fr.CUI.ToString() + "\" denP=\"" + den + "\" "+
							(dupa12_2013?
                            "nrFact=\"" + Convert.ToDouble(fr.NrFact).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ":"") +
                            "baza=\"" +Convert.ToDouble(fr.TotalValoare).ToString("F0", (CultureInfo.InvariantCulture)) + "\" "+
                            "tva=\"" + Convert.ToDouble(fr.TotalValoareTVA).ToString("F0", (CultureInfo.InvariantCulture)) +"\" "+
                            "/>";
                        if (!lista_CUI.Contains(fr.CUI))
                        {
                            CateLinii++;
                            lista_CUI.Add(fr.CUI);
                        }

                    } 
                    #endregion

                    #region Taxare Inversa Achizitii
                    Decimal? rettotalTI = Decimal.Zero, rettotaltvaTI = Decimal.Zero;
                    Decimal? rettotalTIc = Decimal.Zero, rettotaltvaTIc = Decimal.Zero;
                    try { 
                    this.fares_GenereazaD394FacturiTableAdapter.Fill(this.eSRPDataSetListe.fares_GenereazaD394Facturi,
                        ModuleInfo.CodUnitate,
                        delaDTP.Value,
                        panalaDTP.Value,
                        true/*cumparari*/,/*taxare inversa*/true,
                        excludeNrFactTB.Text,
                        ref rettotalTI, ref rettotaltvaTI, ref nrFactC);
                    }
                    catch (Exception)
                    {
                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", Properties.Resources.InvalidDatabaseStructure, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, fares_GenereazaD394FacturiTableAdapter);
                        mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.ShowDialog();
                        return;
                    }

                    this.fares_GenereazaD394ArticoleTableAdapter.Connection = wCon;
                    foreach (DataRowView drv in fares_GenereazaD394FacturiBindingSource)
                    {
                        DataSets.ESRPDataSetListe.fares_GenereazaD394FacturiRow fr = drv.Row as DataSets.ESRPDataSetListe.fares_GenereazaD394FacturiRow;
                        //<op1 tva="25661" baza="106920" denP="TOTO S.R.L." cuiP="4004978" tip="L"/>
                        String den = fr.Denumire.Replace("&", "and");
                        sb2 += "\n<op1 tip=\"C\" cuiP=\"" + fr.CUI.ToString() + "\" denP=\"" + den + "\" "+
							(dupa12_2013?
                            "nrFact=\"" + Convert.ToDouble(fr.NrFact).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ":"") +
                            "baza=\"" + Convert.ToDouble(fr.TotalValoare).ToString("F0", (CultureInfo.InvariantCulture)) + "\" tva=\"" +
                            Convert.ToDouble(fr.TotalValoareTVA).ToString("F0", (CultureInfo.InvariantCulture)) + "\"";
                        if (!lista_CUI.Contains(fr.CUI))
                        {
                            CateLinii++;
                            lista_CUI.Add(fr.CUI);
                        }

                        ///cereale
                        ///
                        Decimal? cerealeB = Decimal.Zero, cerealeTVA = Decimal.Zero;
                        Boolean avemcereale = false;
                        this.fares_GenereazaD394ArticoleTableAdapter.Fill(this.eSRPDataSetListe.fares_GenereazaD394Articole, 
                            fr.CUI,                         
                            delaDTP.Value,
                            panalaDTP.Value,
                            true/*cumparari*/, ref cerealeB, ref cerealeTVA);
                        rettotalTIc += cerealeB;
                        rettotaltvaTIc += cerealeTVA;
                        if (fares_GenereazaD394ArticoleBindingSource.Count != 0)
                            sb2 += ">";
                        foreach (DataRowView dra in fares_GenereazaD394ArticoleBindingSource)
                        {
                            DataSets.ESRPDataSetListe.fares_GenereazaD394ArticoleRow ar = dra.Row as DataSets.ESRPDataSetListe.fares_GenereazaD394ArticoleRow;
                            sb2 += "\n<op11 codPR=\"" + ar.CodPR + "\"  bazaPR=\"" +
                                Convert.ToDouble(ar.BazaPR).ToString("F0", (CultureInfo.InvariantCulture)) + "\" tvaPR=\"" +
                                Convert.ToDouble(ar.TVAPR).ToString("F0", (CultureInfo.InvariantCulture)) + "\" />";
                            avemcereale = true;
                        }
                        if (avemcereale)
                            sb2 += "\n</op1>";
                        else
                            sb2 += " />";

                    } 
                    #endregion

                    #region Livrari
                    Decimal? rettotalL = Decimal.Zero, rettotaltvaL = Decimal.Zero;
                    try { 
                    this.fares_GenereazaD394FacturiTableAdapter.Fill(this.eSRPDataSetListe.fares_GenereazaD394Facturi,
                        ModuleInfo.CodUnitate,
                        delaDTP.Value,
                        panalaDTP.Value,
                        false,/*taxare inversa*/ false,
                        excludeNrFactTB.Text,
                        ref rettotalL, ref rettotaltvaL, ref nrFactL);
                    }
                    catch (Exception)
                    {
                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", Properties.Resources.InvalidDatabaseStructure, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, fares_GenereazaD394FacturiTableAdapter);
                        mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.ShowDialog();
                        return;
                    }

                    foreach (DataRowView drv in fares_GenereazaD394FacturiBindingSource)
                    {
                        DataSets.ESRPDataSetListe.fares_GenereazaD394FacturiRow fr = drv.Row as DataSets.ESRPDataSetListe.fares_GenereazaD394FacturiRow;
                        writeS.WriteLine("#L#," + fr.CUI.ToString() + ",#" + fr.Denumire + "#," +
                            //writeS.WriteLine(dr["CUI"].ToString() + "," + Convert.ToDouble(dr["Total"]).ToString("F2", (CultureInfo.InvariantCulture)) + "," +
                            Convert.ToDouble(fr.TotalValoare).ToString("F2", (CultureInfo.InvariantCulture)) + "," + Convert.ToDouble(fr.TotalValoareTVA).ToString("F2", (CultureInfo.InvariantCulture)));
                        writeS.Flush();
                        String den = fr.Denumire.Replace("&", "and");
                        sb2 += "\n<op1 tip=\"L\" cuiP=\"" + fr.CUI.ToString() + "\" denP=\"" + den + "\" "+
							(dupa12_2013?
                            "nrFact=\"" + Convert.ToDouble(fr.NrFact).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ":"") +
                            "baza=\"" +Convert.ToDouble(fr.TotalValoare).ToString("F0", (CultureInfo.InvariantCulture)) + "\" tva=\"" +
                            Convert.ToDouble(fr.TotalValoareTVA).ToString("F0", (CultureInfo.InvariantCulture)) + "\" />";
                        if (!lista_CUI.Contains(fr.CUI))
                        {
                            CateLinii++;
                            lista_CUI.Add(fr.CUI);
                        }
                    } 
                    #endregion

                    #region Livrari cu taxare inversa
                    Decimal? rettotalLTI = Decimal.Zero, rettotaltvaLTI = Decimal.Zero;
                    Decimal? rettotalLTIc = Decimal.Zero, rettotaltvaLTIc = Decimal.Zero;

                    try { 
                    this.fares_GenereazaD394FacturiTableAdapter.Fill(this.eSRPDataSetListe.fares_GenereazaD394Facturi,
                        ModuleInfo.CodUnitate,
                        delaDTP.Value,
                        panalaDTP.Value,
                        false,/*taxare inversa*/ true,
                        excludeNrFactTB.Text,
                        ref rettotalLTI, ref rettotaltvaLTI,
                        ref nrFactV);
                    }
                    catch (Exception)
                    {
                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", Properties.Resources.InvalidDatabaseStructure, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, fares_GenereazaD394FacturiTableAdapter);
                        mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.ShowDialog();
                        return;
                    }
                    foreach (DataRowView drv in fares_GenereazaD394FacturiBindingSource)
                    {
                        DataSets.ESRPDataSetListe.fares_GenereazaD394FacturiRow fr = drv.Row as DataSets.ESRPDataSetListe.fares_GenereazaD394FacturiRow;
                        String den = fr.Denumire.Replace("&", "and");
                        sb2 += "\n<op1 tip=\"V\" cuiP=\"" + fr.CUI.ToString() + "\" denP=\"" + den + "\" "+
							(dupa12_2013?
                            "nrFact=\"" + Convert.ToDouble(fr.NrFact).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ":"") +
                            "baza=\"" +Convert.ToDouble(fr.TotalValoare).ToString("F0", (CultureInfo.InvariantCulture)) + "\" tva=\"" +
                            Convert.ToDouble(fr.TotalValoareTVA).ToString("F0", (CultureInfo.InvariantCulture)) + "\"";
                        if (!lista_CUI.Contains(fr.CUI))
                        {
                            CateLinii++;
                            lista_CUI.Add(fr.CUI);
                        }

                        ///cereale
                        ///
                        Decimal? cerealeB = Decimal.Zero, cerealeTVA = Decimal.Zero;
                        Boolean avemcereale = false;
                        this.fares_GenereazaD394ArticoleTableAdapter.Fill(this.eSRPDataSetListe.fares_GenereazaD394Articole,
                            fr.CUI,
                            delaDTP.Value,
                            panalaDTP.Value,
                            false/*cumparari*/, ref cerealeB, ref cerealeTVA);
                        rettotalLTIc += cerealeB;
                        rettotaltvaLTIc += cerealeTVA;
                        if (fares_GenereazaD394ArticoleBindingSource.Count != 0)
                            sb2 += ">";
                        foreach (DataRowView dra in fares_GenereazaD394ArticoleBindingSource)
                        {
                            DataSets.ESRPDataSetListe.fares_GenereazaD394ArticoleRow ar = dra.Row as DataSets.ESRPDataSetListe.fares_GenereazaD394ArticoleRow;
                            sb2 += "\n<op11 codPR=\"" + ar.CodPR + "\"  bazaPR=\"" +
                                Convert.ToDouble(ar.BazaPR).ToString("F0", (CultureInfo.InvariantCulture)) + "\" tvaPR=\"" +
                                Convert.ToDouble(ar.TVAPR).ToString("F0", (CultureInfo.InvariantCulture)) + "\" />";
                            avemcereale = true;
                        }
                        if (avemcereale)
                            sb2 += "\n</op1>";
                        else
                            sb2 += " />";



                    }

                    
                    #endregion


                    writeS.Flush();

                    Decimal totalG = Decimal.Zero;
                    //<rezumat tvaCc="0" bazaCc="0" tvaC="0" bazaC="0" tvaVc="0" bazaVc="0" tvaV="0" bazaV="0" tvaA="192456" bazaA="801900" tvaL="25661" bazaL="106920" nrCui="2"/>
                    String sb1 = "\n<rezumat ";
                    if (rettotaltva.HasValue)
                    {
                        sb1 += "tvaA=\"" + Convert.ToDouble(rettotaltva.Value).ToString("F0", (CultureInfo.InvariantCulture))
                       + "\" bazaA=\"" + Convert.ToDouble(rettotal.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                        totalG += Convert.ToDecimal(rettotaltva.Value);
                        totalG += Convert.ToDecimal(rettotal.Value);
                    }
                    else
                        sb1 += "tvaA=\"0\" bazaA=\"0\" ";
                    if (rettotaltvaL.HasValue)
                    {
                        sb1 += "tvaL=\"" + Convert.ToDouble(rettotaltvaL.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" bazaL=\"" +
                        Convert.ToDouble(rettotalL.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                        totalG += Convert.ToDecimal(rettotaltvaL.Value);
                        totalG += Convert.ToDecimal(rettotalL.Value);
                    }
                    else
                        sb1 += "tvaL=\"0\" bazaL=\"0\" ";
                    if (rettotaltvaTI.HasValue)
                    {
                        sb1 += "tvaC=\"" + Convert.ToDouble(rettotaltvaTI.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" bazaC=\"" +
                        Convert.ToDouble(rettotalTI.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                        totalG += Convert.ToDecimal(rettotaltvaTI.Value);
                        totalG += Convert.ToDecimal(rettotalTI.Value);
                    }
                    else
                        sb1 += "tvaC=\"0\" bazaC=\"0\" ";

                    if (rettotaltvaTIc.HasValue)
                    {
                        sb1 += "tvaCc=\"" + Convert.ToDouble(rettotaltvaTIc.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" bazaCc=\"" +
                        Convert.ToDouble(rettotalTIc.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                        totalG += Convert.ToDecimal(rettotaltvaTIc.Value);
                        totalG += Convert.ToDecimal(rettotalTIc.Value);
                    }
                    else
                        sb1 += "tvaCc=\"0\" bazaCc=\"0\" ";

                    if (rettotaltvaLTI.HasValue)
                    {
                        sb1 += "tvaV=\"" + Convert.ToDouble(rettotaltvaLTI.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" bazaV=\"" +
                        Convert.ToDouble(rettotalLTI.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                        totalG += Convert.ToDecimal(rettotaltvaLTI.Value);
                        totalG += Convert.ToDecimal(rettotalLTI.Value);
                    }
                    else
                        sb1 += "tvaV=\"0\" bazaV=\"0\" ";

                    if (rettotaltvaLTIc.HasValue && rettotaltvaLTIc!=Decimal.Zero)
                    {
                        sb1 += "tvaVc=\"" + Convert.ToDouble(rettotaltvaLTIc.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" bazaVc=\"" +
                        Convert.ToDouble(rettotalLTIc.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                        totalG += Convert.ToDecimal(rettotaltvaLTIc.Value);
                        totalG += Convert.ToDecimal(rettotalLTIc.Value);
                    }
                    else
                        sb1 += "tvaVc=\"0\" bazaVc=\"0\" ";


                    if (dupa12_2013)
                    {
                        if (nrFactA.HasValue && nrFactA!=Decimal.Zero)
                        {
                            sb1 += "nrFactA=\"" + Convert.ToDouble(nrFactA.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                            //totalG += Convert.ToDecimal(rettotaltvaLTIc.Value);
                        }
                        else
                            sb1 += "nrFactA=\"0\" ";

                        if (nrFactL.HasValue && nrFactL != Decimal.Zero)
                        {
                            sb1 += "nrFactL=\"" + Convert.ToDouble(nrFactL.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                            //totalG += Convert.ToDecimal(rettotaltvaLTIc.Value);
                        }
                        else
                            sb1 += "nrFactL=\"0\" ";

                        if (nrFactV.HasValue && nrFactV != Decimal.Zero)
                        {
                            sb1 += "nrFactV=\"" + Convert.ToDouble(nrFactV.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                            //totalG += Convert.ToDecimal(rettotaltvaLTIc.Value);
                        }
                        else
                            sb1 += "nrFactV=\"0\" ";

                        if (nrFactC.HasValue && nrFactC != Decimal.Zero)
                        {
                            sb1 += "nrFactC=\"" + Convert.ToDouble(nrFactC.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                            //totalG += Convert.ToDecimal(rettotaltvaLTIc.Value);
                        }
                        else
                            sb1 += "nrFactC=\"0\" ";


                    }

                    totalG += CateLinii;
                    sb1 += " nrCui=\"" + CateLinii.ToString() + "\" />";
                    sbi = "\n<identificare totalPlata_A=\"" + Convert.ToDouble(totalG).ToString("F0", (CultureInfo.InvariantCulture)) + "\" " + sbi;
                    sb += sbi + sb5 + sb1 + sb2 + "\n</declaratie394>";
                    try
                    {
                        xmlDoc.LoadXml(sb);
                    }
                    catch(Exception ex)
                    {
                        writeS.Close();
                        TrateazaExceptie(ex,sb);
                        return;
                    }
                }
                writeS.Close();
                xmlDoc.Save(NumeFisierXml);

                Process retProc = null;
                try

                {
                    //presupunem ca nu are parametrii
                    String savedir = Directory.GetCurrentDirectory();
                    //java -version:1.6 -jar "C:\dist\DUKIntegrator.jar" -s D112 C:/D112.xml $ 0 0 $ 1234 aladdin
                    ProcessStartInfo startInfo = new ProcessStartInfo("java");
                    startInfo.Arguments = "-jar \"" + CaleD394 + "DUKIntegrator.jar\" -p D394 \"" + NumeFisierXml + "\" $ 0 0 $ ";
                    if (SemnatCB.Checked)
                    {
                        startInfo.Arguments = "-jar \"" + CaleD394 + "DUKIntegrator.jar\" -s D394 \"" + NumeFisierXml + "\" $ 0 0 $ " + 
                            PasswordTB.Text + " " + SmartCardCB.Text;
                    }

                    startInfo.WorkingDirectory = CaleD394;
                    MyTrace("Start: " + startInfo.FileName + " args: " + startInfo.Arguments + " working dir: " + startInfo.WorkingDirectory);
                    retProc = Process.Start(startInfo);
                    if(retProc!=null)
                        retProc.WaitForExit();
                    MyTrace("Revenire director aplicatie: " + savedir);
                    Directory.SetCurrentDirectory(savedir);
                }
                catch (Exception ex)
                {
                    MyTrace(ex.Message);
                    if (ex.Message == "The system cannot find the file specified")
                    {
                        MessageBox.Show("Va rugam sa setati calea de lansare a programului DUKIntegrator din meniul Parametrizare Modul!","Atentie");
                        return;
                    }
                    MessageBox.Show(ex.ToString());
                    return;
                }
                if(retProc.ExitCode==0)
                    MessageBox.Show("S-a generat fisierul: " + NumeFisierXml);
            }


        }

        private void Info(object sender, EventArgs e)
        {
            FrmMainMdi frm = this.MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("erpforms");
            if (asm == null)
                return;
            String numeClasa = "ERPForms.UnitatiInfoFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                    new object[] { ModuleInfo, ModuleInfo.CodUnitate }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;
                newFrm.ShowDialog();
            }
            
        }

        private void semestrulCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (semestrulCB.SelectedIndex == 0)
            {
                delaDTP.Value = new DateTime(anulDTP.Value.Year, 1, 1);
                panalaDTP.Value = new DateTime(anulDTP.Value.Year, 6, 30);
                return;
            }
            if (semestrulCB.SelectedIndex == 1)
            {
                delaDTP.Value = new DateTime(anulDTP.Value.Year, 7, 1);
                panalaDTP.Value = new DateTime(anulDTP.Value.Year, 12, 31);
                return;
            }


        }

        private void trimestrulRB_CheckedChanged(object sender, EventArgs e)
        {
            if (sender == semestrulRB)
            {
                semestrulCB.Enabled = true;
                trimestrulCB.Enabled = false;
                lunaCB.Enabled = false;
                delaDTP.Value = new DateTime(anulDTP.Value.Year, 1, 1);
                panalaDTP.Value = new DateTime(anulDTP.Value.Year, 6, 30);
                semestrulCB.SelectedIndex = 0;
            }
            else
                if (sender == trimestrulRB)
                {
                    semestrulCB.Enabled = false;
                    lunaCB.Enabled = false;
                    trimestrulCB.Enabled = true;
                    delaDTP.Value = new DateTime(anulDTP.Value.Year, 1, 1);
                    panalaDTP.Value = new DateTime(anulDTP.Value.Year, 3, 31);
                    trimestrulCB.SelectedIndex = 0;
                }
                else
                    if (sender == lunaRB)
                    {
                        semestrulCB.Enabled = false;
                        trimestrulCB.Enabled = false;
                        lunaCB.Enabled = true;
                        delaDTP.Value = new DateTime(anulDTP.Value.Year, 1, 1);
                        panalaDTP.Value = new DateTime(anulDTP.Value.Year, 1, 31);
                        lunaCB.SelectedIndex = 0;
                    }
        }

        private void trimestrulCB_SelectedIndexChanged(object sender, EventArgs e)
        {

            DateTime ultima = new DateTime(((trimestrulCB.SelectedIndex + 1) * 3 + 1) > 12?anulDTP.Value.Year:anulDTP.Value.Year+1,
                ((trimestrulCB.SelectedIndex + 1) * 3 + 1) > 12 ? 1 : (trimestrulCB.SelectedIndex + 1) * 3 + 1, 1);
            delaDTP.Value = new DateTime(anulDTP.Value.Year, trimestrulCB.SelectedIndex*3+1, 1);
            panalaDTP.Value = new DateTime(anulDTP.Value.Year, (trimestrulCB.SelectedIndex+1) * 3 , ultima.AddDays(-1).Day);
        }

        private void lunaCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            DateTime ultima = new DateTime((lunaCB.SelectedIndex  + 2) > 12 ? anulDTP.Value.Year : anulDTP.Value.Year + 1,
               (lunaCB.SelectedIndex + 2) > 12 ? 1 : lunaCB.SelectedIndex +  2, 1);
            delaDTP.Value = new DateTime(anulDTP.Value.Year, lunaCB.SelectedIndex + 1, 1);
            panalaDTP.Value = new DateTime(anulDTP.Value.Year, lunaCB.SelectedIndex + 1, ultima.AddDays(-1).Day);
        }

        private void anulDTP_ValueChanged(object sender, EventArgs e)
        {
            delaDTP.Value = new DateTime(anulDTP.Value.Year, delaDTP.Value.Month, delaDTP.Value.Day);
            panalaDTP.Value = new DateTime(anulDTP.Value.Year, panalaDTP.Value.Month, panalaDTP.Value.Day);

        }

        

       

       


    }
}
